package md.frolov.bible.commands;



import md.frolov.bible.editors.BibleEditorInput;
import md.frolov.bible.editors.MainEditor;
import md.frolov.bible.model.Archive;
import md.frolov.bible.toolbars.NavigationTextContribution;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IParameter;
import org.eclipse.core.commands.NotEnabledException;
import org.eclipse.core.commands.NotHandledException;
import org.eclipse.core.commands.Parameterization;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.handlers.IHandlerService;

public class OpenEditorCommand extends AbstractHandler implements IHandler {
	public static final String ID = "md.frolov.bible.commands.openEditor";
	public static final String PARM_URL_ID = "md.frolov.bible.commands.openEditor.url";

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
			try {
				String url = event.getParameter(PARM_URL_ID);
				if(url == null){
					String yok = NavigationTextContribution.getTextContribution().getText();
					if(yok==null) return null;
					url = Archive.getInstance().getUrlForStringLocation(yok);
					if(url==null) return null;
				}
				HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().openEditor(new BibleEditorInput(url), MainEditor.PLUGIN_ID);
			} catch (PartInitException e) {
				e.printStackTrace();
			}
		return null;
	}

	public static void executeStatic(String url){
		try {
			IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
			ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
			
			Command goToCommand = commandService.getCommand(OpenEditorCommand.ID);
			IParameter parameter = null;
		
			parameter = goToCommand.getParameter(OpenEditorCommand.PARM_URL_ID);
			Parameterization parm = new Parameterization(parameter,url);
			handlerService.executeCommand(new ParameterizedCommand(goToCommand, new Parameterization[]{parm}), null);
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotDefinedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotEnabledException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotHandledException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
